package org.seed.rpc.core;

import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 当前节点注册检查工具
 */
@Slf4j
public class EndpointChecker implements Job {


    public EndpointChecker() {
    }


    /**
     * 注册的key
     */
    private static String key;

    /**
     * 当前服务节点
     */
    private static String endpoint;


    /**
     * 注册中心客户端
     */
    private static RegistryClient registryClient;


    private static Scheduler scheduler;

    static {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Trigger trigger = TriggerBuilder
                .newTrigger()
                .withIdentity("EndpointCheckerJobTrigger", "EndpointCheckerJobTriggerGroup")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5)
                        .repeatForever())
                .build();
        try {
            scheduler = schedulerFactory.getScheduler();
            JobDetail jobDetail = JobBuilder.newJob(EndpointChecker.class)
                    .withIdentity("EndpointCheckerJob", "EndpointCheckerJobGroup")
                    .build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 启动节点已注册检查
     *
     * @param key
     * @param endpoint
     * @param registryClient
     */
    public static void start(String key, String endpoint, RegistryClient registryClient) {
        setKey(key);
        setEndpoint(endpoint);
        setRegistryClient(registryClient);
        try {
            scheduler.start();
        } catch (Exception e) {

        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String endpointStore = registryClient.get(key);
        if (endpointStore == null || endpointStore.trim().equals("")) {
            registryClient.put(key, endpoint);
            log.warn("✘  key:{},endpoint: {} registry not found, register again", key, endpoint);
            return;
        }
        log.debug("✔  registry storage checked ok. \uD83D\uDE04");
    }


    private static void setKey(String key) {
        EndpointChecker.key = key;
    }

    private static void setEndpoint(String endpoint) {
        EndpointChecker.endpoint = endpoint;
    }

    private static void setRegistryClient(RegistryClient registryClient) {
        EndpointChecker.registryClient = registryClient;
    }

}
